package top.huhuiyu.study.servlet.employee;

import top.huhuiyu.study.dao.TbDeptDAO;
import top.huhuiyu.study.dao.TbEmployeeDAO;
import top.huhuiyu.study.entity.Result;
import top.huhuiyu.study.entity.TbDept;
import top.huhuiyu.study.entity.TbEmployee;
import top.huhuiyu.study.util.JsonUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "employeeadd", urlPatterns = "/employee/add.action")
public class AddServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
        try {
            Integer dept_id = Integer.parseInt(req.getParameter("dept_id"));
            String username = req.getParameter("username");
            String sex = req.getParameter("sex");
            Long salary = Long.parseLong(req.getParameter("salary"));
            // 验证部门编号是否正确！！！
            TbDept dept = TbDeptDAO.queryById(dept_id);
            if (dept == null) {
                Result<String> result = Result.fail("部门不存在", null);
                writer.println(JsonUtils.stringify(result));
                return;
            }
            TbEmployee employee = new TbEmployee();
            employee.setDept_id(dept_id);
            employee.setUsername(username);
            employee.setSex(sex);
            employee.setSalary(salary);
            int i = TbEmployeeDAO.insert(employee);
            if (i == 1) {
                Result<String> result = Result.success("添加成功");
                writer.println(JsonUtils.stringify(result));
            } else {
                Result<String> result = Result.fail("添加失败", null);
                writer.println(JsonUtils.stringify(result));
            }
        } catch (Exception e) {
            e.printStackTrace();
            Result<String> result = Result.fail("添加发生错误", null);
            writer.println(JsonUtils.stringify(result));
        }
    }
}
